package com.lanjiu.lib.communication.timer;

import com.lanjiu.pro.business.BusinessProtocolMessageStandard;
import com.lanjiu.lib.communication.interf.IMSClientInterface;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.util.internal.StringUtil;

/**
 * @description: 消息发送超时管理器，用于管理消息定时器的新增、移除等
 * @author: Panwei
 * @date: 2019/10/28 14:30
 */
public class MsgTimeoutTimerManager {

    private Map<String, MsgTimeoutTimer> mMsgTimeoutMap;
    private IMSClientInterface mImsClient;// ims客户端

    public MsgTimeoutTimerManager(IMSClientInterface imsClient) {
        this.mMsgTimeoutMap = new ConcurrentHashMap<>();
        this.mImsClient = imsClient;
    }

    /**
     * 添加消息到发送超时管理器
     *
     * @param msg
     */
    public void add(BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage msg) {
        if (msg == null)
            return;
        BusinessProtocolMessageStandard.UnifiedEntranceMessage unifiedEntranceMessage = msg.getUnifiedEntranceMessage();
        if (unifiedEntranceMessage.getDataType() != BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType.FriendChatProtocol
                && unifiedEntranceMessage.getDataType() != BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType.GroupChatProtocol) {
            // 如果不是聊天消息类型，不加入发送超时管理器
            return;
        }
        String msgId = msg.getUnifiedEntranceMessage().getHead().getUniqueIdentify();
        if (!mMsgTimeoutMap.containsKey(msgId)) {
            MsgTimeoutTimer timer = new MsgTimeoutTimer(mImsClient, msg);
            mMsgTimeoutMap.put(msgId, timer);
        }
    }

    public void remove(String msgId) {
        if (StringUtil.isNullOrEmpty(msgId)) return;
        if (mMsgTimeoutMap.containsKey(msgId)) {
            MsgTimeoutTimer timer = mMsgTimeoutMap.get(msgId);
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            mMsgTimeoutMap.remove(msgId);
        }
    }

    public boolean hasSending() {
        return mMsgTimeoutMap.size() > 0;
    }

    public synchronized void onResetConnected() {
        for (Iterator<Map.Entry<String, MsgTimeoutTimer>> it = mMsgTimeoutMap.entrySet().iterator(); it.hasNext(); ) {
            it.next().getValue().send();
        }
    }
}
